package com.example.ftdatabase;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class TaskTranslator {
	// Database fields
		private SQLiteDatabase database;
		private TaskSQLiteHelper helper;
		private String[] allColumns = { TaskSQLiteHelper.COLUMN_ID,
				TaskSQLiteHelper.COLUMN_TASK };
		
		public TaskTranslator(Context context) {
			helper = new TaskSQLiteHelper(context);
		}
		
		public void open() throws SQLException {
			database = helper.getWritableDatabase();
		}
		
		public void close() {
			helper.close();
		}
		
		public Task createTask(String name, int length, Date date, boolean isRecurring) {
			String strTask = name + ", " + length + ", " + date.toString() + ", ";
			if(isRecurring) strTask += "1";
			else strTask += "0";
			ContentValues values = new ContentValues();
			values.put(TaskSQLiteHelper.COLUMN_TASK, strTask);
			long insertId = database.insert(TaskSQLiteHelper.TABLE_TASKS, null,
					values);
			Cursor cursor = database.query(TaskSQLiteHelper.TABLE_TASKS,
					allColumns, TaskSQLiteHelper.COLUMN_ID + " = " + insertId, null,
					null, null, null);
			cursor.moveToFirst();
			Task newTask= cursorToTask(cursor);
			cursor.close();
			return newTask;
		}
		
		public void deleteTask(Task t) {
			long id = t.getId();
			System.out.println("Task deleted with id: " + id);
			database.delete(TaskSQLiteHelper.TABLE_TASKS, TaskSQLiteHelper.COLUMN_ID
					+ " = " + id, null);
		}
		
		public List<Task> getAllTasks() {
			List<Task> tasks = new ArrayList<Task>();

			Cursor cursor = database.query(TaskSQLiteHelper.TABLE_TASKS,
					allColumns, null, null, null, null, null);

			cursor.moveToFirst();
			while (!cursor.isAfterLast()) {
				Task t = cursorToTask(cursor);
				tasks.add(t);
				cursor.moveToNext();
			}
			// Make sure to close the cursor
			cursor.close();
			return tasks;
		}
		
		private Task cursorToTask(Cursor cursor) {
			StringTokenizer strTok = new StringTokenizer(cursor.getString(1), ", ");
			Task t;
			try {
				DateFormat df = DateFormat.getDateInstance();
				t = new Task(strTok.nextToken(), Integer.parseInt(strTok.nextToken()),
						df.parse(strTok.nextToken()), (Integer.parseInt(strTok.nextToken()) == 1)? true: false);
			} catch (Exception e) {
				System.err.println("Error reading from database.");
				t = new Task("Go outside", 5, new Date(), true);
			}
			t.setId(cursor.getLong(0));
			return t;
		}

}
